<template>
  <view class="phone-login-area">
    <view class="account-login-area">
      <view class="privacy-guide">
        <text class="guide-text">
          注册需要获取您的手机号用于账户验证，地址信息用于服务定位（可选）
        </text>
      </view>

      <view class="box account">
        <wd-icon name="person" size="15px"></wd-icon>
        <wd-text text="姓名：" color="#000"></wd-text>
        <wd-input placeholder="请输入姓名" v-model="formData.realname"></wd-input>
        <!-- 移除了获取微信信息的按钮 -->
      </view>
      <!-- <view class="box account">
        <wd-icon name="photo" size="15px"></wd-icon>
        <wd-text text="头像：" color="#000"></wd-text>
        <view class="avatar-upload">
          <online-image v-model:value="formData.avatar" name="avatar" :maxNum="1" :limitSize="2" />
        </view>
      </view> -->
      <view class="box account">
        <wd-icon name="location" size="15px"></wd-icon>
        <wd-text text="地址：" color="#000"></wd-text>
        <wd-input placeholder="请输入或选择地址" v-model="formData.address"></wd-input>
        <button class="custom-phone-button" @click="goToLocationPage" style="margin-left: 10px">
          选择地址
        </button>
      </view>
      <view class="box account">
        <wd-icon name="mobile" size="15px"></wd-icon>
        <wd-text text="电话：" color="#000"></wd-text>
        <wd-input placeholder="请输入手机号" v-model="formData.phone"></wd-input>
        <button
          class="custom-phone-button"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
          style="margin-left: 10px"
        >
          获取微信手机号
        </button>
      </view>
    </view>

    <view class="btn-area text-center">
      <wd-button custom-class="login align-top" :loading="loading" @click="handleRegister">
        {{ loading ? '注册中...' : '注册' }}
      </wd-button>

      <view class="switch-login-way">
        <text class="switch-login-way-text" @click="$emit('switch-way', 2)">短信登陆</text>
        <text
          class="switch-login-way-text"
          @click="$emit('switch-way', 0)"
          style="margin-left: 20px"
        >
          快捷登录
        </text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useToast } from 'wot-design-uni'
import { useLocationStore } from '@/store/location'
import { http } from '@/utils/http'
import { userApi } from '@/api/api'
import OnlineImage from '@/components/online/view/online-image.vue'

interface Props {
  loading?: boolean
}

interface Emits {
  (e: 'update:loading', value: boolean): void
  (e: 'switch-way', value: number): void
  (e: 'register-success'): void
}

interface RegisterForm {
  realname: string
  address: string
  avatar: string
  phone: string
  openid: string
  latitude?: number
  longitude?: number
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
})

const emit = defineEmits<Emits>()

const toast = useToast()
const locationStore = useLocationStore()

const formData = reactive<RegisterForm>({
  realname: '',
  address: '',
  avatar: '',
  phone: '',
  openid: '',
  latitude: undefined,
  longitude: undefined,
})

// 初始化时从store加载地址
if (locationStore.selectedLocation) {
  formData.address = locationStore.selectedLocation.address
  formData.latitude = locationStore.selectedLocation.latitude
  formData.longitude = locationStore.selectedLocation.longitude
}

// 跳转到地图选择页面
const goToLocationPage = () => {
  if (locationStore.selectedLocation) {
    locationStore.setTempLocation(locationStore.selectedLocation)
  }

  uni.navigateTo({
    url: '/pages-user/location/location',
  })
}

// 监听位置变化
const unsubscribe = locationStore.$subscribe((mutation, state) => {
  if (state.selectedLocation) {
    formData.address = state.selectedLocation.address
    formData.latitude = state.selectedLocation.latitude
    formData.longitude = state.selectedLocation.longitude
  }
})

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      // 这里可以添加上传逻辑
      // 暂时直接使用本地路径作为预览
      formData.avatar = tempFilePath

      // 如果需要上传到服务器，可以使用以下代码模板:
      // uploadAvatar(tempFilePath)
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
    },
  })
}

// 组件卸载时取消订阅
onUnmounted(() => {
  unsubscribe()
})

// 获取微信手机号
const getPhoneNumber = async (e: any) => {
  try {
    // #ifdef MP-WEIXIN
    if (e.detail && e.detail.errMsg !== 'getPhoneNumber:ok') {
      throw new Error('用户拒绝了授权')
    }

    const [loginRes, phoneRes] = await Promise.all([
      new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject,
        })
      }),
      Promise.resolve(e.detail ? e.detail.code : null),
    ])

    const params = {
      userCode: loginRes.code,
      code: phoneRes,
    }

    const res = await http.post(userApi.getUserPhoneByWx, params)

    if (res.success) {
      // 只需要将手机号填入表单，不执行登录操作
      formData.phone = res.result.phone
      formData.openid = res.result.openid
    } else {
      throw new Error(res.message || '获取手机号失败')
    }
    // #endif
    // #ifndef MP-WEIXIN
    // 非微信环境模拟数据
    console.log('现在使用的是非微信环境')
    formData.phone = '13272408547'
    // #endif
  } catch (err: any) {
    toast.warning(err.message || '获取手机号失败')
  }
}

const handleRegister = () => {
  const { realname, address, avatar, phone, openid, latitude, longitude } = formData
  const checkPhone = /^[1]([3-9])[0-9]{9}$/

  if (!realname) {
    toast.warning('请输入姓名')
    return
  }
  if (!address) {
    toast.warning('请输入地址')
    return
  }
  if (!phone) {
    toast.warning('请输入手机号')
    return
  }
  if (!checkPhone.test(phone)) {
    toast.warning('请输入正确的手机号')
    return
  }

  emit('update:loading', true)

  const registerParams = {
    realname,
    address,
    avatar,
    phone,
    openid,
    latitude,
    longitude,
  }

  http
    .post(userApi.regisUserForMini, registerParams)
    .then((res: any) => {
      if (res.success) {
        toast.success('注册成功!')
        // 重置表单
        Object.assign(formData, {
          realname: '',
          address: '',
          avatar: '',
          phone: '',
          latitude: undefined,
          longitude: undefined,
        })
        // 清除位置存储
        locationStore.clearLocation()
        emit('register-success')
        emit('switch-way', 0) // 注册成功后切换到登录界面
      } else {
        toast.warning(res.message || '注册失败')
      }
    })
    .catch((err: any) => {
      const msg = err.message || '请求出现错误，请稍后再试'
      toast.warning(msg)
    })
    .finally(() => {
      emit('update:loading', false)
    })
}

// 暴露表单数据供父组件访问
defineExpose({
  formData,
})
</script>

<style lang="scss" scoped>
.phone-login-area {
  .privacy-guide {
    background-color: #f0f8ff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 20px;
    text-align: center;

    .guide-text {
      color: #666;
      font-size: 14px;
      line-height: 1.4;
    }
  }
  .account-login-area {
    .box {
      display: flex;
      align-items: center;
      min-height: 100upx;
      color: #000;
      border: 1px solid #eee;
      background-color: #fff;
      padding: 0 20upx;
      margin-bottom: 30upx;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);

      :deep(.wd-text) {
        margin: 0 10upx;
      }

      :deep(.wd-input),
      :deep(.uni-input) {
        flex: 1;
        &::after {
          height: 0;
        }
      }
    }
  }

  .btn-area {
    :deep(.login) {
      margin-right: 30px;
      width: 100%;
      margin-right: 0;
      margin-bottom: 20px;
    }

    :deep(.wd-button) {
      --wot-button-medium-height: 41px;
      --wot-button-medium-fs: 16px;
      --wot-button-plain-bg-color: transparent;
      min-width: 100px;
      box-shadow: 3px 3px 4px rgba(0, 102, 204, 0.2);
    }
  }

  .switch-login-way {
    text-align: center;
    margin-top: 20px;

    .switch-login-way-text {
      color: #007aff;
      font-size: 14px;
    }
  }
}
.custom-phone-button {
  margin-left: 10px;
  background: transparent; /* 透明背景 */
  padding: 0 8px; /* 内边距 */
  height: 28px; /* 高度匹配 wd-button */
  line-height: 28px;
  font-size: 12px; /* 字体大小 */
  color: #333; /* 文字颜色 */
  border: 1px solid #ddd; /* 边框 */
  border-radius: 4px; /* 圆角 */
}

/* 如果需要 hover 效果 */
.custom-phone-button:hover {
  opacity: 0.8;
}

.avatar-upload {
  display: flex;
  align-items: center;
  flex: 1;

  .upload-btn {
    font-size: 12px;
  }
}
.user-avatar {
  width: 70px;
  height: 70px;
  margin-left: 10px;
  border-radius: 50%;
  border: 2px solid #dbdbdb;
}
</style>
